/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  "jquery",
  "pageInit",
  "formValidator",
  "formAjax",
  "notification",
  "select2"
], function($, vamakerPage, formValidator, formAjax, VamOpMsg, select2) {
  $(function() {
    var 
      $appSelectedList = $('#app_selected_list'),
      $appSizeList = $('#app_size_list'),
      $appFormatList = $('#app_format_list'),
      $packType = $('.pack-type'),
      appToPackList = VAM.getVar('APP_TO_PACK_LIST'),
      appSizeAndFormatList = VAM.getVar('APP_SIZE_FORMAT_LIST'),
      appSizeListRender, appFormatListRender;

    appSizeListRender = function (data) {
      var
        sizeList = '',
        len = data.length;
      if (len !== 0) {
        for(var i = 0; i < len; i++) {
          if (i < 1) {
            sizeList += '<span class="list-item">' + data[i] + '</span>';
          } else {
            sizeList += '<span class="list-item">，' + data[i] + '</span>';
          }
        }

        $appSizeList.html(sizeList);
      }
    };

    appFormatListRender = function (data) {
      var
        formatList = '',
        len = data.length;
      if (len !== 0) {
        for(var i = 0; i < len; i++) {
          if (i < 1) {
            formatList += '<span class="list-item">' + data[i] + '</span>';
          } else {
            formatList += '<span class="list-item">，' + data[i] + '</span>';
          }
        }

        $appFormatList.html(formatList);
      }
    };

    $appSelectedList.select2({
      language: "zh-CN",
      placeholder: VAM.j('Select APP name'),
      ajax: {
        data: function (params) {
          var $packTypeChecked = $packType.filter(':checked'),
            trafficArr = [];
          var query = {
            search: params.term,
            type: $packTypeChecked.val()
          };

          return query;
        },
        url: appToPackList,
        dataType: 'json',
        delay: 1000,
        processResults: function (data) {
          return {
            results: data.items
          }
        },
        cache: true
      },
      minimumInputLength: 1,
    });

    $packType.on('change', function (evt) {
      $appSelectedList.val(null).trigger('change');
    });

    $appSelectedList.on('change', function (evt) {
      var
        $me = $(this),
        meVal = $me.val();
      // console.log($(this).val());
      $.ajax({
        url: appSizeAndFormatList,
        type: 'get',
        data: {
          app: meVal
        }
      })
      .done(function(data) {
        if (data.status === 'success') {
          appSizeListRender(data.data.sizeList);
          appFormatListRender(data.data.formatList);
        } else {
          VamOpMsg.messager(data);
        };
      })
      .fail(function() {
        console.log('error!');
      })
      .always(function() {
        $me.trigger('blur');
      });
    })
  });

  $(function() {
    var $dataFrm = $("#data-frm"),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      dataFieldRule,
      options,
      dataValidator;
    // console.log($dataFrm);
    dataFieldRule = {
      pack_name: {
        rule: {
          required: {
            message: VAM.j("Pack name cannot be empty")
          },
          maxlength: {
            param: 32,
            message: VAM.j("Pack name for a maximum of 32 characters")
          }
        },
        messageContainer: "pack_name_err"
      },
      app_selected_list: {
        rule: {
          required: {
            message: VAM.j("App list cannot be empty")
          }
        },
        messageContainer: 'app_selected_list_err'
      },
      floor_price:{
        rule:{
          required:{
            message: VAM.j('Floor price cannot be empty')
          },
          floatnumber:{
            message: VAM.j('Input correct number')
          },
          validnum1: {
            param: $('#ceiling_price'),
            message: VAM.j('Please input the floor price')
          }
        },
        messageContainer:'floor_price_err'
      },
      ceiling_price:{
        rule:{
          required:{
            message: VAM.j('Ceiling price cannot be empty')
          },
          floatnumber:{
            message: VAM.j('Input correct number')
          },
          validnum2: {
            param: $('#floor_price'),
            message: VAM.j('The floor price cannot exceed the ceiling price')
          }
        },
        messageContainer:'ceiling_price_err'
      }
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function(evt) {
        if (evt.resultList.length <= 0) {
          $dataFrm.ajaxSubmit({
            beforeSubmit: function() {
              $submitBtn.button("loading");
            },
            success: function(data) {
              $submitBtn.button("reset");
              if (data.status === "success") {
                VamOpMsg.messager(data);
                window.location.href = "/pack/manage";
              } else {
                VamOpMsg.messager(data);
              }
            }
          });
        }
      }
    };
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    dataValidator.addRule("effectiveNumber", function(val, opt) {
      return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
    });
    dataValidator.addRule("required", function(val, opt) {
      if (opt === "password") {
        return !!(val && !/^(?:\s\w|\u3000)+$/.test(val));
      } else {
        return !!(val && !/^(?:\s|\u3000)+$/.test(val));
      }
    });
    dataValidator.addRule('validnum1', function(val, opt) {
      if (opt.val() === '') {
        return true;
      }
      opt.trigger('blur');
      return true;
    });
    dataValidator.addRule('validnum2', function(val, opt) {
      if (opt.val() === '') {
        opt.trigger('blur');
        return true;
      }
      return parseInt(opt.val()) <= parseInt(val);
    });
  });
});
